<template>
    <div class="tree">
        <div class="left">
            <stock-tree ref="treeRef" @node-click="nodeClick"></stock-tree>
        </div>
        <div class="right">
            <view-grid ref="grid" :columns="columns" :detail="detail" :details="details" :editFormFields="editFormFields"
                :editFormOptions="editFormOptions" :searchFormFields="searchFormFields"
                :searchFormOptions="searchFormOptions" :table="table" :extend="extend" :onInit="onInit" :onInited="onInited"
                :searchBefore="searchBefore" :searchAfter="searchAfter" :addBefore="addBefore" :updateBefore="updateBefore"
                :rowClick="rowClick" :modelOpenBefore="modelOpenBefore" :modelOpenAfter="modelOpenAfter"
                :tableAddRowBefore="tableAddRowBefore">
                <!-- 自定义组件数据槽扩展，更多数据槽slot见文档 -->
                <template #gridHeader>
                </template>
            </view-grid>
        </div>
    </div>
    <select-material ref="materialRef" @onSelectMaterial="onSelectMaterial"></select-material>
    <select-LotText ref="lotMasterDetailRef" @onSelectLotText="onSelectLotText"></select-LotText>
</template>
<script setup lang="jsx">
import extend from "@/extension/scm/scm/PeriodInventory.jsx";
import viewOptions from './PeriodInventory/options.js'
import StockTree from './StockTree.vue'
import SelectMaterial from './PeriodInventorySelectMaterial.vue'
import SelectLotText from './PeriodInventorySelectLot.vue'
import { ref, reactive, getCurrentInstance, nextTick, watch, onMounted } from "vue";
const grid = ref(null);
const { proxy } = getCurrentInstance()
//http请求，proxy.http.post/get
const { table, editFormFields, editFormOptions, searchFormFields, searchFormOptions, columns, detail, details } = reactive(viewOptions())
const materialRef = ref();
const lotMasterDetailRef = ref();

let gridRef;//对应[表.jsx]文件中this.使用方式一样
let period = ref();
//生成对象属性初始化
const onInit = async ($vm) => {
    gridRef = $vm;
    initPeriodInfo()
    //与jsx中的this.xx使用一样，只需将this.xx改为gridRef.xx
    //更多属性见：https://doc.volcore.xyz/docs/view-grid
}
//生成对象属性初始化后,操作明细表配置用到
const onInited = async () => {
    gridRef.buttons.splice(3, 0, {
        name: '结束初始化', //按钮名称
        icon: 'el-icon-document',
        type: 'primary',
        plain: true,
        onClick: () => {

            savePeriodInventoryData()
        }
    })
    columns.forEach((column) => {

        if (column.field == 'MaterialNo') {
            column.render = (h, { row, column, index }) => {
                column.edit = null;//设置当前字段不可编辑
                return (
                    <div style=" display: flex !important;justify-content: space-between !important;">
                        <span style="margin-right:5px">{row.MaterialNo}</span>
                        <el-button link
                            onClick={($e) => {
                                $e.stopPropagation();
                                //触发事件
                                materialRef.value.open(nodeData)

                            }}
                            class="el-icon-search"
                            style="color: #2196F3;cursor: pointer;"
                        ></el-button>
                    </div>
                );
            };
        }
        if (column.field == 'LotText') {
            column.edit = { type: "selectTable" }
            column.readonly = false;

            //尽量自定义接口，见下面的文档描述，或者Demo_GoodsController类的方法Search
            column.url = 'api/PeriodInventory/lotSearch';

            //设置显示的字段
            column.columns = [
                { field: 'LotMasterDetailId', title: '批号明细标识', type: 'string', hidden: true },
                { field: 'LotText', title: '批号', type: 'string', width: 100, search: true },
            ];

            //rows:选中的行
            column.onSelect = (editRow, rows) => {
                editRow.LotMasterDetailId = rows[0].LotMasterDetailId;
                editRow.LotText = rows[0].LotText;
            };


            column.loadBefore = (editRow, param, callback) => {

                param.value = editRow.MaterialId;
                callback(true);
            };

            //表格数据加载后处理
            //editRow:当前正在编辑的行
            //rows:后台返回的数据
            column.loadAfter = (editRow, rows, callback, result) => {
                callback(true);
            };

            /****下面的这些都是可以选配置，上面的是必填的******/
            //监听输入框变动与回车事件
            column.onKeyPress = (val, $event, row) => {
                console.log(val);
                if ($event.keyCode == 13) {
                    console.log('按了回车');
                }
                //清空值时给其他字段设置值
                // if(!val&&value+''!='0'){
                //     row.xx=null;
                // }
            }
            //设置弹出框高度(默认200)
            column.height = 200;
            //设置弹出框宽度(默认500)
            column.selectWidth = 800;
            column.textInline = true; //设置表格超出显示...
            //设置表格是否单选
            column.single = true;
            //隐藏分页
            column.paginationHide = true;
            //设置默认分页大小与分页信息
            column.pagination = { size: 30, sizes: [30, 60, 90] };
        }
    });


    columns.forEach(c => {
        if (c.field == 'StockId') {
            //如果字段是下拉框或日期，添加onChange事件
            c.onChange = (row, column, event) => {
                selectChange(row, column)
            }
        }
        if (c.field == 'LotText') {
            c.checkEdit = (row, column, index) => {
                //可根据row.字段的值返回true/false是否可以编辑
                return row.IsLoted == 1
            }
        }
        if (c.field == 'LocationId') {
            c.checkEdit = (row, column, index) => {
                //可根据row.字段的值返回true/false是否可以编辑
                return row.IsLocation == 1
            }
        }
        if (c.field == 'AssistUnitQty') {
            c.checkEdit = (row, column, index) => {
                //可根据row.字段的值返回true/false是否可以编辑
                return row.IsAssistUnit == 1
            }
        }
        if (c.field == 'StartQty') {
            //将eidt设置为null不开启编辑
            c.formatter = (row) => {
                //给当前列同时设置上值
                if (row.StartQty == 0) {
                    row.CostPrice
                }
                else {
                    row.CostPrice = ((row.StartAmount || 0) / row.StartQty).toFixed(4);
                }
                //调用明细表合计
                // this.$refs.updateSummary(['要刷新的字段1','要刷新的字段2']);
                //可以设置计算规则 ，如：
                //return row.字段1 * row.字段2
                //返回table显示的值
                return row.StartQty
            }
        }
        if (c.field == 'CostPrice') {
            //将eidt设置为null不开启编辑
            c.numberLength = 4
        }
    })

}
const selectChange = (row, column) => {
    //找到第二个下拉框选项
    let col = columns.find((c) => { return c.field == 'LocationId' })
    let url = 'api/Location/getLocationByStockId'
    //从后台返回第二个下拉框满足条件的数据
    proxy.http.post(url, row.StockId, false).then((locationInfos) => {
        //keys只返回第二个下拉框的key值，用于下面的判断，返回的下拉框key选项显示，没有返回的隐藏
        console.log(locationInfos)
        col.bind.data.forEach((item) => {
            console.log(item)
            console.log(item.key)
            console.log(locationInfos[0] == item.key)

            //注意：第二个下拉框选项，在下拉框绑定页面，配置的字典sql需要将全部数据源返回
            //如果返回的数据源有几十W，请考虑用弹出框选择数据，不要用下拉框
            if (locationInfos.indexOf(item.key + '') != -1) {
                console.log(item.key)
                item.hidden = false
            } else {
                console.log(item.key)
                item.hidden = true
            }
        })
    })
}
const savePeriodInventoryData = () => {

    var rows = gridRef.getTable(true).rowData;
    proxy.http.post('/api/PeriodInventory/updateDatas', rows, true)
        .then((x) => {
            proxy.$message.info('保存成功');
            return;
        });
}

const searchBefore = async (param) => {
    if (catalogIds != null) {
        param.wheres.push({
            name: 'StockId', //查询分类字段，注意字段大小写
            value: catalogIds,
            displayType: 'selectList'
        })

        return true
    } else {
        return false
    }

}
const searchAfter = async (rows, result) => {


    return true;
}
const addBefore = async (formData) => {
    //新建保存前formData为对象，包括明细表，可以给给表单设置值，自己输出看formData的值
    return true;
}
const updateBefore = async (formData) => {
    //编辑保存前formData为对象，包括明细表、删除行的Id
    return true;
}
const rowClick = ({ row, column, event }) => {
    //查询界面点击行事件
    //如果字段是下拉框或日期，添加onChange事件
    selectChange(row, column)

    grid.value.toggleRowSelection(row); //单击行时选中当前行;
}
const modelOpenBefore = async (row) => {//弹出框打开后方法
    return true;//返回false，不会打开弹出框
}
const modelOpenAfter = (row) => {
    //弹出框打开后方法,设置表单默认值,按钮操作等
}
const tableAddRowBefore = (row) => {
    row.PeriodYear = period.PeriodYear
    row.PeriodMonth = period.PeriodMonth
    row.IsLoted = 0
    row.StockId = nodeData[1]
    row.IsLocation = 0

    return true
}

const initPeriodInfo = () => {

    let url = 'api/Period/getCurrentPeriod';
    proxy.http.post(url).then((result) => {
        // detailRow.value.PeriodYear = result.periodYear
        // detailRow.value.PeriodMonth = result.periodMonth
        period.PeriodYear = result.periodYear
        period.PeriodMonth = result.periodMonth
    });
}
let catalogIds
let nodeData
//左边树点击事件
const nodeClick = (ids, nodes) => {
    //左边树节点点击事件
    //左边树节点的甩有子节点，用于查询数据
    catalogIds = ids.join(',')
    //左侧树选中节点的所有父节点,用于新建时设置级联的默认值
    nodeData = nodes
    nextTick(() => {
        //调用查询方法
        gridRef.search()

    })
}
const onSelectMaterial = (rows) => {
    gridRef.search()
}
const onSelectLotText = (row) => {

}


//监听表单输入，做实时计算
//watch(() => editFormFields.字段,(newValue, oldValue) => {	})
//对外暴露数据
defineExpose({})
</script>
<style scoped lang="less">
.tree {
    display: flex;

    .left {
        width: 200px;
    }

    .right {
        flex: 1;
        width: 0;
    }
}
</style>